package JDBC;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class classDao {
    public static void insert(ClassModel classModel) throws SQLException {
        Connection connection = DBUtil.getConnection();
        String sql = "insert into class values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,classModel.getId());
        statement.setString(2,classModel.getName());

        int ret = statement.executeUpdate();
        System.out.println("ret="+ ret);
    }

    public static List<ClassModel> selectAll() throws SQLException {
        List<ClassModel> list = new ArrayList<>();

        Connection connection = DBUtil.getConnection();
        String sql = "select * from class";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            ClassModel classModel = new ClassModel();
            classModel.setId(resultSet.getInt("id"));
            classModel.setName(resultSet.getString("name"));
            list.add(classModel);
        }

        return list;
    }

    public static void main(String[] args) throws SQLException {
        ClassModel classModel = new ClassModel();
        classModel.setId(6);
        classModel.setName("土木工程");
        List<ClassModel> list = selectAll();
        for (ClassModel classes : list) {
            System.out.println(classes.toString());
        }
    }
}
